<?php

namespace App\Http\Controllers\OA;

use App\Http\Controllers\Controller;
use App\Http\Requests\NoticeRequest;
use App\Http\Resources\NoticeResource;
use App\Model\OANotice;
use Carbon\Carbon;
use Illuminate\Http\Request;

class NoticeController extends Controller
{
    //添加公告
    public function addNotice( NoticeRequest $request)//NoticeRequest
    {
        try {
            $notice = OANotice::query()->create($request->validated());
            return $this->SucRes(['id' => $notice->id]);
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }

    public function getNotice(Request $request)
    {
        try {
            $data = OANotice::query()
                ->when($request->filled('keywords') && $request->keywords, function ($q) use ($request) {
                    return $q->where('title', 'like', trim($request->keywords) . "%")->orWhere('content', 'like', trim($request->keywords) . "%");
                })
                ->when($request->filled('publish_at') && $request->publish_at, function ($q) use ($request) {
                    return $q->whereBetween('publish_at', [
                        Carbon::parse($request->publish_at[0])->toDateTimeString(),
                        Carbon::parse($request->publish_at[1])->toDateTimeString(),
                    ]);
                })
                ->paginate($request->limit ?? 10);
            return $this->SucRes(NoticeResource::collection($data));
        }catch (\Exception $e){
            dd($e);
        }
    }

    //修改公告
    public function editNotice(OANotice $notice,NoticeRequest $request)
    {

        $notice->fill($request->all())->save();
        return $this->SucRes();
    }

    //删除公告
    public function delNotice(OANotice $notice)
    {
        $notice->delete();
        return $this->SucRes();
    }
}
